package com.maixun.lib_base.ui.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.maixun.lib_base.R

/**
 * @author:Lmoumou
 * @date:2020/9/3
 * 描述:
 **/
abstract class BaseDialogImpl : DialogFragment(), BaseDialog {
    protected lateinit var mContext: Context
    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mContext = context
    }

    override fun onStart() {
        super.onStart()
        dialog?.let {
            val params = it.window?.attributes
            params?.width = getDialogWith()
            params?.height = getDialogHeight()
            params?.gravity = getGravity()
            params?.dimAmount = getDimAmount()
            params?.windowAnimations = getAnimationResId()
            it.window?.attributes = params
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.BaseFragmentDialog)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val layoutId = getLayoutId()
        return if (layoutId < 0) {
            super.onCreateView(inflater, container, savedInstanceState)
        } else {
            inflater.inflate(layoutId, container, false)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view, savedInstanceState)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return super.onCreateDialog(savedInstanceState).apply {
            isCancelable = isCanBackKey()
            setCanceledOnTouchOutside(isCanBlank())
        }
    }

    override fun isShowIng(): Boolean {
        return this.dialog?.isShowing ?: false
    }

    override fun dismissThis(isResume: Boolean) {
        if (isResume) {
            dismiss()
        } else {
            dismissAllowingStateLoss()
        }
    }

    override fun showThis(manager: FragmentManager, tag: String) {
        if (!this.isAdded && this.dialog?.isShowing != true) {
            val ft = manager.beginTransaction()
            ft.add(this, tag)
            ft.commitAllowingStateLoss()
        }
    }
}